import React, { Component } from 'react';
import { NavBar, SwipeAction } from 'antd-mobile'
import { Stepper } from 'antd-mobile'
import '../../styles/Shopcar.scss'
import { Checkbox, Space } from 'antd-mobile'
// import { QuestionCircleOutline } from 'antd-mobile-icons'
import service from '../../api'
import car from '../../assets/car.png'
class Shopcar extends Component {
    constructor(props) {
        super(props)
        this.state = {
            carlist: [],
            cart: [],
            userid: '',
            cartid: '',
            num: '',
            length: 0,
            sum: 0,
            flag: false,
            allSelected: false,
            isshow: false,
            time: '',
            rightActions: [{
                key: 'delete',
                text: '删除',
                color: 'danger',
                flag: false,

            }],
            right: (<div style={{ fontSize: 16 }} onClick={() => { this.toRemoveAll() }}>
                <Space style={{ '--gap': '16px' }}>
                    清空购物车
                </Space>
            </div>)
        }
    }
    async componentDidMount() {
        var res = await service.pro.pro_recommendlist()
        this.setState({ carlist: res.data.data })
        // 渲染购物车列表,删除所有的购物车数据
        var res1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
        // 判断数据的数组的长度位0的时候设置管理状态位false,渲染空标签，否则渲染数据
        if (res1.data.data.length == 0) {
            this.setState({ isshow: false })
        } else {
            this.setState({ isshow: true })
            this.setState({ cart: res1.data.data })
        }
        var arr = res1.data.data && res1.data.data.filter((item0) => {
            return item0.flag == true
        })
        if (arr) {
            var sum = arr.reduce((prev, item0) => {
                return prev += item0.originprice * item0.num
            }, 0)
            var leng = arr.reduce((prev, item0) => {
                return prev += item0.num
            }, 0)
            this.setState({ sum, length: leng })
            if (arr.length == res1.data.data.length) {
                this.setState({ flag: !this.state.flag })
            }
        }

    }
    // 单个商品删除
    async delete(cartid) {
        var result = await service.shopcar.cart_remove({ cartid: cartid })
        var result1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
        this.setState({ cart: result1.data.data })
    }
    // 删除所有的商品
    async allclear() {
        await service.shopcar.cart_removeall({ userid: localStorage.getItem('userid') })
    }
    //  更新商品数量
    async shangadd(value, item0) {
        var res = await service.shopcar.cart_updatenum({ cartid: item0, num: value })
        var res1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
        var arr = res1.data.data.filter((item0) => {
            return item0.flag == true
        })
        var sum = arr.reduce((prev, item0) => {
            return prev += item0.originprice * item0.num
        }, 0)
        var leng = arr.reduce((prev, item0) => {
            return prev += item0.num
        }, 0)
        this.setState({ list: res1.data.data, sum, length: leng })
    }
    //单选按钮操作
   async selectone(item) {
    item.flag=!item.flag
        let allChecked = this.state.allChecked;
        let tag = this.state.cart.every((item) => { return item.flag })
        allChecked = tag;
        this.setState({
            cart: this.state.cart,
            allChecked: allChecked,
            flag: !this.state.flag
        })
        this.getToTal()
       var selectoneres =  service.shopcar.cart_selectone({ cartid: item.cartid, flag: item.flag })
       if(selectoneres.data.code==200){
        var res1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
        this.setState({ cart: res1.data.data })
       }
    }
    //全选按钮操作
   async selectall() {
        let allChecked = !this.state.allChecked
        this.state.cart.map((item) => { item.flag = allChecked })
        this.setState({
            cart: this.state.cart,
            allChecked: allChecked
        })
        this.getToTal()
        var allCheckedres = await service.shopcar.cart_selectall({userid:localStorage.getItem('userid'),type:allChecked})
        if(allCheckedres.data.code == 200){
            var allSelecters = await service.shopcar.cart_list({userid:localStorage.getItem('userid')})
            this.setState({cart:allSelecters.data.data})
        }
    }
    //计算总价
    getToTal() {

        let total = 0;
        let num = 0;
        let newlist = this.state.cart.filter((item) => { return item.flag == true });
        newlist.map((item) => {
            total += item.originprice * item.num

        })
        this.setState({
            sum: total,

        })
    }

    // // 选中单个商品
    // async selectone(val, cartid) {
    //     var res = await service.shopcar.cart_selectone({ cartid: cartid, flag: val })
    //     var res1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
    //     this.setState({ cart: res1.data.data })
    //     var arr = res1.data.data.filter((item0) => {
    //         return item0.flag == true
    //     })
    //     if (arr.length == res1.data.data.length) {
    //         this.setState({ flag: !this.state.flag })
    //     } else {
    //         this.setState({ flag: false })
    //     }
    // }
    // // 选中所有商品
    // async selectall(val) {
    //     var res = await service.shopcar.cart_selectall({ userid: localStorage.getItem('userid'),type:val })
    //     var res1 = await service.shopcar.cart_list({ userid: localStorage.getItem('userid') })
    //     console.log(res1.data.data);
    //     var arr = res1.data.data.filter((item0)=>{
    //         return item0.flag == true
    //     })
    //     var sum = arr.reduce((prev,item0)=>{
    //         return prev +=item0.originprice*item0.num
    //     },0)
    //     var leng = arr.reduce((prev,item0)=>{
    //         return prev +=item0.num
    //     },0)
    //     this.setState({cart:res.data.data,flag:!this.state.flag})
    // }
    back() {
        this.props.history.go(-1)
    }
    cate() {
        this.props.history.push('/index/cate')
    }
    detail() {
        this.props.history.push('/detail')
    }
    todetail(proid) {
        this.props.history.push('/detail/' + proid)
    }
    async shop() {
        var res = await service.order.order_addOrder({ userid: localStorage.getItem('userid') })

        this.props.history.push('/order')
        localStorage.setItem('time', JSON.stringify(res.data.time))
        localStorage.setItem('sum', JSON.stringify(this.state.sum))

    }
    render() {
        return (
            <div className='shopcar'>
                <div className="fan">
                    <NavBar onBack={() => { this.back() }}>购物车</NavBar>
                    <div className="clear" onClick={() => { this.allclear() }}>清空购物车</div>
                </div>
                <div className="shops">
                    {
                        this.state.isshow == false ? <img src={car} className='kong' alt="" /> : this.state.cart.map((item0, index) => {
                            return (
                                <SwipeAction key={index} rightActions={this.state.rightActions} onAction={() => { this.delete(item0.cartid, index) }}>
                                    <div className="name" key={index}>
                                        <div className="inp">
                                            <input type="checkbox" checked={item0.flag} onChange={() => { this.selectone(item0) }} />
                                        </div>
                                        <div className="imags">
                                            <img src={item0.img1} alt="" />
                                        </div>
                                        <div className="word">
                                            <div className="text">{item0.proname}</div>
                                            <div className="price">
                                                <span className='originprice'>￥{item0.originprice}</span>
                                                <div className="num">
                                                    <Stepper min={1} max={999} defaultValue={item0.num} onChange={(value) => { this.shangadd(value, item0.cartid) }} />
                                                    {/* <div className="add" onChange={(value) => { this.shangadd(value, item0.cartid) }}>+</div>
                                                    <span>{item0.num}</span>
                                                    <div className="sub"  defaultValue={item0.num}>-</div> */}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </SwipeAction>
                            )
                        })
                    }

                </div>
                <div className="detail" onClick={() => { this.detail() }}>
                    快点来看看
                </div>
                <div className="carlist">
                    {
                        this.state.carlist.map((item, index) => {
                            return (
                                <div className="list" key={index} onClick={() => { this.todetail(item.proid) }}>
                                    <img src={item.img3} alt="" />
                                    <div className="name">{item.proname}</div>
                                    <div className="price">￥{item.originprice}</div>
                                </div>
                            )
                        })
                    }
                </div>
                <div className="goodcar">
                    <div className="left">
                        <Checkbox onChange={(val) => { this.selectall(val) }} checked={this.state.allSelected}>全选</Checkbox>
                    </div>
                    <div className="right">
                        <div className="sums">
                            合计：{this.state.sum}
                        </div>
                        <button onClick={() => { this.shop() }}>去结算</button>
                    </div>
                </div>
            </div>
        );
    }
}

export default Shopcar;